"use client";
import { useEffect, useState } from 'react';
import CategoryLayout from '../components/CategoryLayout';
import axios from 'axios';
import { Kbd, Button } from 'flowbite-react';
import { Card } from 'flowbite-react';
import Link from 'next/link';
// import BlogForceGraph from '../components/BlogForceGraph';
import BlogForceGraph from '../components/BlogForceGraph';
import { Accordion } from 'flowbite-react';
import { motion } from "motion/react"
import { useScroll } from 'motion/react';
// import { myPlugin } from '../components/Doub
export default function Archive() {
    const { scrollYProgress } = useScroll();
    const [archive, setArchive] = useState({});

    const [category, setCategory] = useState("");
    const [allCategory, setAllCategory] = useState([]);

    const [graphNode, setGraphNode] = useState({
        "nodes": [
            { "id": "node1", "label": "Node 1", "value": 10, "group": 1 },
            { "id": "node2", "label": "Node 1", "value": 10, "group": 1 },
        ],
        "links": [
            { "source": "node1", "target": "node2" },
        ]
    });

    function transformGraphNode(items) {


        var blogLinks = items.filter((it) => it.links.length != 0).reduce((acc, obj) => {
            return acc.concat(obj.links.reduce((acc, item) => {
                acc["source"] = obj.id;
                acc["target"] = item;
                return acc;
            }, {}))
        }, [])


        const graphData = {
            "nodes": items,
            "links": blogLinks
        }
        // console.log(graphData);
        setGraphNode(graphData);

    }

    useEffect(() => {
        const fetchData = async () => {
            const response = await axios.get("/api/blog");
            const blogData = response.data;

            const groupByYearAndMonth = {};


            var allCategory = blogData.reduce((acc, obj) => {
                return acc.concat(obj.category)
            }, [])
            allCategory = [...new Set(allCategory)]
            setAllCategory(allCategory);
            blogData.forEach(item => {
                item.id = item.path;
                item.label = item.filePath.split("\\").pop().split(".md")[0];
                item.group = item.category.join(",");
            })
            transformGraphNode(blogData);
            blogData.filter(item => {

                if (category == "") {
                    return true;
                }
                if (item.category.indexOf(category) != -1) {
                    // console.log("as")
                    return true;
                }
                return false;
            }).forEach(item => {
                const date = new Date(item.modifyTime);
                // 获取年份和月份（格式为 YYYY-MM）
                const yearMonth = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2);
                const fullYear = date.getFullYear();
                const fullMonth = ('0' + (date.getMonth() + 1)).slice(-2);
                if (!groupByYearAndMonth[fullYear]) {
                    groupByYearAndMonth[fullYear] = {};

                }
                const groupByMonth = groupByYearAndMonth[fullYear];
                // 如果分组对象中还没有这个年份和月份，则初始化一个空数组
                if (!groupByMonth[fullMonth]) {
                    groupByMonth[fullMonth] = [];
                }
                item.modifyYearAndMonth = yearMonth;

                // 将当前项添加到对应的年份和月份数组中
                groupByMonth[fullMonth].push(item);
                groupByYearAndMonth[fullYear] = groupByMonth;
            })

            setArchive(groupByYearAndMonth);

            // var categorys= blogData.reduce((acc, obj) => {
            //     return acc.concat(obj.category)
            // }, [])
            // categorys = [...new Set(categorys)]
            // setCategorys(categorys)
        };
        fetchData();
    }, [category])


    function handleCategoryClick(name) {
        setCategory(name);
    }


    function BlogArchive() {
        return (
            <div >

                <div className="flex flex-wrap gap-2 p-4">
                    <Button onClick={() => handleCategoryClick("")}  >所有分类</Button>
                    {
                        allCategory.map((item) => (
                            <Button outline gradientDuoTone="purpleToPink" onClick={() => handleCategoryClick(item)} key={item} >
                                {item}
                            </Button>
                        ))
                    }
                </div>

                {/* <Kbd onClick={()=>handleCategoryClick("")} >所有分类</Kbd> */}
                {/* <Button onClick={() => handleCategoryClick("")}  >所有分类</Button> */}
                {/* <div className='pt-3'>
                    {category !== "" && <Kbd className='p-3'>{category}</Kbd>}
                </div> */}
                <Accordion>
                    <Accordion.Panel>
                        <Accordion.Title>文章关联</Accordion.Title>
                        <Accordion.Content>
                            <div className='grid place-items-center'>
                                <BlogForceGraph graphData={graphNode} showLabel={false} />
                            </div>

                        </Accordion.Content>
                    </Accordion.Panel>

                </Accordion>
                <motion.div
                id="scroll-indicator"
                style={{
                  scaleX: scrollYProgress,
                  position: "fixed",
                  top: 0,
                  left: 0,
                  right: 0,
                  height: 10,
                  originX: 0,
                  backgroundColor: "#ff0088",
                }}
            />

                {Object.keys(archive).reverse().map((year) => (
                    <div key={year}>
                        <h1 className='text-2xl font-bold'>{year}年</h1>
                        {Object.keys(archive[year]).reverse().map((month) => (
                            <div key={month}>
                                <h3 className='text-sm text-gray-400 p-2'>{month}月</h3>
                                <div className='grid grid-cols-3 gap-2'>
                                    {archive[year][month].map((item) => (

                                        <Card className="max-w-sm" key={item.path}>
                                            <div className="flex flex-wrap gap-2">
                                                {

                                                    item.category.map(item => (
                                                        <Kbd key={item} onClick={() => handleCategoryClick(item)} >{item}</Kbd>
                                                    ))
                                                }
                                            </div>
                                            <h5 className="text-xl font-bold tracking-tight text-gray-900 dark:text-white">
                                                <Link key={item.path} href={"/blogs/" + item.path}>
                                                    {item.filePath.split("\\").pop().split(".md")[0]}
                                                </Link>
                                            </h5>

                                        </Card>

                                    ))}
                                </div>

                            </div>
                        ))}
                    </div>
                ))}


            </div>
        );
    }

    return <CategoryLayout>

        <BlogArchive></BlogArchive>
        {/* 
        <h1>卡片盒</h1>
        <div className="flex flex-wrap gap-2">
            {

                categorys.map(category => (
                    <Kbd key={category}>{category}</Kbd>
                ))
            }
        </div> */}

    </CategoryLayout>
}

